<template>
  <div class="stats-task-chart-wrap">
    <div class="stats-task-chart">
      <div id="event-type-chart" ref="chart"></div>
      <stats-chart-empty v-if="isEmpty">{{$t('common.base.tip.noData')}}</stats-chart-empty> 
    </div>
    <div class="stats-task-table-wrap" v-if="showTable">
      <div class="stats-task-table-header">
         <h3>{{ $t('report.stationTable.title2') }}</h3>
        <button type="button" class="btn btn-primary btn-sm" @click="exportData" v-if="isButtonDisplayed && exportAuth">{{ $t('common.base.export') }}</button> 
        <button type="button" class="btn btn-primary btn-sm" @click="exportAllData" v-if="isButtonDisplayed && exportAuth">{{ $t('common.base.exportAll') }}</button> 
        <button type="button" class="btn btn-primary btn-sm" @click="showTable = false">{{ $t('common.base.collapse') }}</button>
      </div>
      <div class="stats-task-table">
        <el-table :data="page.list" class="stats-table">

          <el-table-column :label="$t('common.base.serialNumber')" prop="eventNo" width="150px" :show-overflow-tooltip="false">
            <template slot-scope="scope">
              <sample-tooltip :row="scope.row">
                <template slot="content" slot-scope="{isContentTooltip}">
                  <el-tooltip :content="scope.row.eventNo" placement="top" :disabled="!isContentTooltip">
                    <a href="#" @click="openDetail(scope.row)">{{scope.row.eventNo}}</a>
                  </el-tooltip>
                </template>
              </sample-tooltip>
            </template>
          </el-table-column>
          <el-table-column :label="$t('common.base.customer')" prop="cusName"></el-table-column>
          <el-table-column :label="$t('common.label.eventType')" prop="templateName" width="180px"></el-table-column>
          
          <el-table-column :label="$t('common.label.principalName')" width="120px">
            <template slot-scope="scope">
              <template v-if="isOpenData">
                <open-data type="userName" :openid="scope.row.executorStaffId"></open-data>
              </template>
              <template v-else>
                {{ scope.row.executorName }}
              </template>
            </template>
          </el-table-column>

          <el-table-column :label="$t('common.base.createUser')" width="120px">
            <template slot-scope="scope">
              <template v-if="isOpenData">
                <open-data type="userName" :openid="scope.row.createUserStaffId"></open-data>
              </template>
              <template v-else>
                {{ scope.row.createUserName }}
              </template>
            </template>
          </el-table-column>
 
        </el-table>

        <el-pagination class="stats-pagination"
                       background @current-change="jump"
                       :current-page="page.pageNum"
                       layout="total, prev, pager, next"
                       :total="page.total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { isOpenData, openAccurateTab } from '@src/util/platform';
import echarts from 'packages/Echarts';
import _ from 'lodash';
import qs from 'src/util/querystring';
import SampleTooltip from 'packages/SampleTooltip';
import { checkButtonDisplayed } from '@src/util/dom';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
let chart = null;
import { t } from '@src/locales'
import { dayTimeStart, dayTimeEnd, downloadFileByLink } from 'pub-bbx-utils';
export default {
  name: 'event-type-chart',
  props: {
    chartData: Object,
    timeStart: [Number, String],
    timeEnd: [Number, String],
    exportTrack: Function
  },
  data(){
    return {
      isButtonDisplayed: checkButtonDisplayed(),
      isOpenData,
      isEmpty: false,
      showTable: false,
      
      model: {
        pageNum: 1,
        templateName: ''
      },
      page: {}
    }
  },
  computed: {
    exportAuth() {
      let initData = JSON.parse(sessionStorage.getItem('_init_data'))
      return initData.auths?.REPORT_EXPORT || 0
    },
  },
  methods: {
    exportAllData(){
      let model = {}

      if(this.timeStart) model.timeStart = +dayTimeStart(this.timeStart);
      if(this.timeEnd) model.timeEnd = +dayTimeEnd(this.timeEnd);

      downloadFileByLink(`/api/report/outside/stats/station/eventCount/exportAll?${ qs.stringify(model)}`)

      this.exportTrack(true)
    },
    exportData(){
      let model = {
        templateName: this.model.templateName
      }

      if(this.timeStart) model.timeStart = +dayTimeStart(this.timeStart);
      if(this.timeEnd) model.timeEnd = +dayTimeEnd(this.timeEnd);
      
      downloadFileByLink(`/api/report/outside/stats/station/eventCount/export?${ qs.stringify(model)}`)

      this.exportTrack(false)
    },
  
    openDetail(row){
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `eventView_${ row.id}`, 
      //   title: `事件${row.eventNo}`, 
      //   close: true, 
      //   url: `/event/view/${row.id}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageEventView,
        key: row.id,
        titleKey: row.eventNo,
        fromId
      })
    },
    jump(currentPage){
      this.model.pageNum = currentPage;
      this.renderTable();
    },
    init(){
      chart = echarts.init(this.$refs.chart);
      chart.on('click', event => {
        let origin = event.data._origin;
        
        this.model.pageNum = 1;
        this.model.templateName = origin.eventType;
        
        this.renderTable()
      })

      let ctx = this;
      window.addEventListener('resize', _.debounce(function () {
        ctx.render();
      }, 400));
    },
    render(){
      this.showTable = false;
      chart.clear();
      let arr = this.chartData.eventType || {};

      let eventType = [];

      for(let name in arr){
        if(arr[name] && arr[name] > 0) eventType.push({
          eventType: name,
          count: arr[name]
        });
      }

      if(eventType.length == 0){
        this.isEmpty = true;
        return 
      }
      
      this.isEmpty = false;

      let taskTypeLegend = [];
      let taskTypeSeries = [];
      let taskTypeData = [];
      let sum = 0;
      
      eventType.forEach(item => {
        sum += item.count

        let legend = item.eventType;
        taskTypeLegend.push(legend);

        taskTypeData.push({
          name: legend,
          value: item.count,
          _origin: item
        });
      });
     
      
      taskTypeSeries.push({
        name: t('common.form.type.serviceType'),
        type: 'pie',
        radius : '55%',
        center: ['50%', '55%'],
        label: {
          normal: {
            formatter: '{b}： {c} ({d}%)'
          }
        },
        data: taskTypeData,
        itemStyle: {
          normal: {label : {show: true}},
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      })
      
      let taskTypeOption = this.getOptions(taskTypeLegend, taskTypeSeries, `${t('report.callConsultChart.total')}：${ sum}`)
            
      chart.resize();

      chart.setOption(taskTypeOption);
    },
    getOptions(legend, series, title){
      return {
        color: ['#2ec7c9', '#ffb980', '#5ab1ef', '#d87a80', '#5f5f6e', '#07a2a4', '#9a7fd1', '#588dd5', '#c05050', '#f5994e', '#59678c', '#7eb00a', '#749f83'],
        tooltip : {
          trigger: 'item',
          formatter:`{b} <br/> ${t('common.label.count')}: {c} ({d}%)`
        },
        title: {
          show: true,
          subtext: title,
          right: 100,
          top: 5,
          subtextStyle: {
            color: '#666',
            fontSize: 14
          }
        },
        toolbox: {
          right: 40,
          top: 10,
          feature: {
            saveAsImage: {
              name: t('report.taskProductChart.text3'),
            }
          }
        },
        grid: {
          left: 120,
          containLabel: true
        },
        legend: {
          top: 10,
          bottom: 10,
          left: 5,
          orient: 'vertical',
          data: legend,
          type: 'scroll'
        },
        series
      }
    },
    fetchTableData(){
      let model = {
        pageNum: this.model.pageNum,
        templateName: this.model.templateName,
        pageSize: 10
      };
      if(this.timeStart) model.timeStart = +dayTimeStart(this.timeStart);
      if(this.timeEnd) model.timeEnd = +dayTimeEnd(this.timeEnd);
      return this.$http.post('/api/report/outside/stats/station/eventCount/detail', model);
    },
    async renderTable(){
      let instance = this.$loading.show(this.$el);
        
      this.fetchTableData().then(result => {
        this.page = result;
        this.showTable = true;
      })
        .catch(err => console.log(err))
        .finally(() => {
          instance.hide();
        })
    },
    
  },
  mounted(){
    this.init();
  },
  activated(){    
    this.render();
  },
  watch: {
    chartData: {
      deep: true,
      handler(value) {
        this.render();
      }
    }
  },
  components: {
    [SampleTooltip.name]: SampleTooltip,
  }
}
</script>
